import 'package:flutter/material.dart';
import 'package:flutter_provider_demo/data/repositories/auth_repository.dart';
import 'package:flutter_provider_demo/ui/cart/cart_screen.dart';
import 'package:flutter_provider_demo/ui/cart/cart_viewmodel.dart';
import 'package:flutter_provider_demo/ui/catalog/catalog_screen.dart';
import 'package:flutter_provider_demo/ui/login/login_screen.dart';
import 'package:flutter_provider_demo/ui/login/login_viewmodel.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

abstract final class Routes {
  static const String login = '/login';
  static const String catalog = '/catalog';
  static const String cart = '/cart';
}

GoRouter router(
  AuthRepository authRepository,
) =>
    GoRouter(
      initialLocation: Routes.catalog,
      redirect: _redirect,
      refreshListenable: authRepository,
      routes: [
        GoRoute(
          path: Routes.login,
          builder: (context, state) => LoginScreen(
            viewModel: LoginViewModel(
              authRepository: context.read(),
            ),
          ),
        ),
        GoRoute(
          path: Routes.catalog,
          builder: (context, state) => CatalogScreen(
            viewModel: context.read(),
          ),
        ),
        GoRoute(
          path: Routes.cart,
          builder: (context, state) => CartScreen(
            viewModel: CartViewModel(
              cartRepository: context.read(),
            ),
          ),
        ),
      ],
    );

Future<String?> _redirect(BuildContext context, GoRouterState state) async {
  if (state.matchedLocation == Routes.catalog) {
    return null;
  }
  final authRepository = context.read<AuthRepository>();
  final isLogin = await authRepository.isLogin();
  final isLoginPage = state.matchedLocation == Routes.login;

  if (!isLogin) {
    if (isLoginPage) {
      return null;
    }
    return '${Routes.login}?from=${state.matchedLocation}';
  }

  if (isLoginPage) {
    return Routes.catalog;
  }

  return null;
}
